﻿using System.Net.Sockets;
using System.Text;

string serverIP = "127.0.0.1";
int port = 10086;
string[] messages = {"hello server.","How are you","I'm fine,thank you" };
//1.创建客户端对象
using (TcpClient tcpClient = new TcpClient())
{
    //2.链接服务端
   await tcpClient.ConnectAsync(serverIP, port);
    Console.WriteLine("client connected!");
    //3.客户端收发内容流对象
    using(NetworkStream stream = tcpClient.GetStream())
    {
        foreach(var message in messages)
        {
            //转换字符串城字节数组
            byte[] data=Encoding.ASCII.GetBytes(message);
            //4.发送内容给服务端
            await stream.WriteAsync(data, 0, data.Length);
            Console.WriteLine($"sent:{message}");
            byte[] buffer=new byte[1024];
            //5.接收服务端内容
            int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
            if(bytesRead > 0)
            {
                string response=Encoding.ASCII.GetString(buffer,0,bytesRead);
                Console.WriteLine($"received:{response}");
            }
        }
    }
}

Console.WriteLine("client disconnected!");